import React, { useState, ReactNode, useEffect } from "react";
import * as auth from "auth-provider";
import { message } from "antd";
import { useMount } from "utils/index";
import { User } from "../screen/project-list/search-panel";
import { handleUserRespinse } from "auth-provider";
import { vertifyLogin } from "service/login/index";
import { useAsync } from "utils/index";
import { FullErrorPage, FullLoading } from "components/lib";
interface typemjc {
  user: User | null;
  login: (form: AuthForm) => any;
  register: (form: AuthForm) => any;
  loginout: () => Promise<void>;
}
interface mjc {
  code?: number;
  message?: string;
  userInfo: User;
  data?: Array<[]>;
}
const AuthContext = React.createContext<typemjc | undefined>(undefined);

export interface AuthForm {
  username: string;
  password: string;
}
AuthContext.displayName = "AuthContext";

export const AuthProvide = ({ children }: { children: ReactNode }) => {
  const {
    data: user,
    error,
    isLoading,
    isIdle,
    isError,
    run,
    setData: setuser,
  } = useAsync<User | null>(undefined, {
    thorwOnError: true,
  });
  // const [user, setuser] = useState<User | null>(null);
  const login = async (form: AuthForm) => {
    try {
      const result = await auth.login<mjc>(form);
      if (result) {
        setuser(result.userInfo || null);
        handleUserRespinse(result.userInfo || null);
      }
    } catch (error) {
      return Promise.reject(error);
    }
  };
  const register = async (form: AuthForm) => {
    try {
      const result = await auth.register(form);
      return [];
    } catch (error) {
      return Promise.reject(error);
    }
  };
  const loginout = async () => {
    setuser(null);
  };
  useMount(async () => {
    try {
      await run(vertifyLogin<mjc>());
    } catch (error: any) {
      message.error(error?.message);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  });
  if (isIdle || isLoading) {
    return <FullLoading></FullLoading>;
  }
  // if (isError) {
  //   return <FullErrorPage error={error}></FullErrorPage>;
  // }
  // message.error(error?.message);
  const obj = {
    login,
    user,
    register,
    loginout,
  };
  return <AuthContext.Provider children={children} value={obj} />;
};
export const useAuth = () => {
  const context = React.useContext(AuthContext);
  if (!context) {
    throw new Error("userAuth");
  }
  return context;
};
